package com.qiankan.qmsj.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qiankan.qmsj.Constants;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.UserInfo;
import com.qiankan.qmsj.db.UserDBHelper;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.utils.ProviderUtil;
import com.qiankan.qmsj.utils.StringUtils;
import com.qiankan.qmsj.utils.UploadUtils;
import com.qiankan.qmsj.widget.TipToast;
import com.xingchen.ListPopWindow;
import com.xingchen.PopBean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersionInfoActivity extends BaseActivity implements ListPopWindow.OnBottomTextviewClickListener {
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_culture)
    TextView tvCulture;
    @BindView(R.id.tv_purpose)
    TextView tvPurpose;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    @BindView(R.id.tv_credit)
    TextView tvCredit;
    @BindView(R.id.real_name)
    TextView realName;
    @BindView(R.id.tv_phone)
    TextView telPhone;
    @BindView(R.id.et_identify)
    EditText identify;
    @BindView(R.id.imageView)
    ImageView imgHeader;
    @BindView(R.id.rl_job)
    RelativeLayout rlJob;
    @BindView(R.id.rl_culture)
    RelativeLayout rlCulture;
    @BindView(R.id.rl_purpose)
    RelativeLayout rlPurpose;
    @BindView(R.id.rl_record)
    RelativeLayout rlRecord;
    @BindView(R.id.rl_credit)
    RelativeLayout rlCredit;
    private ListPopWindow popWindow;
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int REQUEST_ALBUM = 1; //打开相册
    public static final int REQUEST_CAPTURE = 2; //拍照
    public static final int REQUEST_CROP = 3; //裁剪
    public static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 100;
    private UserInfo userInfo;
    private File picture;
    private File corpFile;//裁剪后的图片文件

    public static Intent newIntent(Context context) {
        return new Intent(context, PersionInfoActivity.class);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_persion_info;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        picture = new File(getExternalCacheDir(), "header.png");
        userInfo = UserDBHelper.getInstance(this).getUserInfo();
        if (userInfo == null) {
            Intent intent = LogInActivity.newIntent(this);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return;
        }
        showLoadingDialog();
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", userInfo.getId());
        param.put("phone", userInfo.getPhone());
        APIHub.getsInstance().getBaseService().getUserInfo(param).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                dismissLoadingDialog();
                Result result = response.body();
                if (result.getCode().equals("200")) {
                    userInfo = new Gson().fromJson(result.getData(), UserInfo.class);
                    UserDBHelper.getInstance(PersionInfoActivity.this).saveUserInfo(userInfo);
                    initView();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                dismissLoadingDialog();
            }
        });
    }

    private void initView() {
        AsyncLoadImage.loadImageRound(userInfo.getHead(), imgHeader);
        realName.setText(userInfo.getName());
        telPhone.setText(userInfo.getPhone());
        identify.setText(userInfo.getIdcard());
        tvJob.setText(userInfo.getProfession());
        tvCulture.setText(userInfo.getCulture());
        tvPurpose.setText(userInfo.getPurpose());
        tvRecord.setText(userInfo.getLoans());
        tvCredit.setText(userInfo.getCredit());
    }

    public void showJon(View view) {
        final List<PopBean> pops = new ArrayList<>();
        pops.add(new PopBean("学生族", 0));
        pops.add(new PopBean("工薪族", 1));
        pops.add(new PopBean("企业族", 2));
        pops.add(new PopBean("自由族", 3));
        pops.add(new PopBean("其他", 4));
        popWindow = new ListPopWindow(this, new ListPopWindow.OnPopItemClickListener() {
            @Override
            public void onPopItemClick(View view, int position) {
                tvJob.setText(pops.get(position).getTitle());
                popWindow.dismiss();
            }
        }, this, rlJob, pops, "取消", "请选择职业");
        //  popWindow.setAnimationStyle(R.style.pop_anim);
        popWindow.showAtLocation(rlJob, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    }

    public void showCulture(View view) {
        final List<PopBean> pops = new ArrayList<>();
        pops.add(new PopBean("大专及以上", 0));
        pops.add(new PopBean("本科", 1));
        pops.add(new PopBean("硕士", 2));
        pops.add(new PopBean("博士及以上", 3));
        pops.add(new PopBean("其他", 4));
        popWindow = new ListPopWindow(this, new ListPopWindow.OnPopItemClickListener() {
            @Override
            public void onPopItemClick(View view, int position) {
                tvCulture.setText(pops.get(position).getTitle());
                popWindow.dismiss();
            }
        }, this, rlCulture, pops, "取消", "请选择文化程度");
        //  popWindow.setAnimationStyle(R.style.pop_anim);
        popWindow.showAtLocation(rlCulture, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    }

    public void showPurpose(View view) {
        final List<PopBean> pops = new ArrayList<>();
        pops.add(new PopBean("购房", 0));
        pops.add(new PopBean("购车", 1));
        pops.add(new PopBean("其他", 2));
        popWindow = new ListPopWindow(this, new ListPopWindow.OnPopItemClickListener() {
            @Override
            public void onPopItemClick(View view, int position) {
                tvPurpose.setText(pops.get(position).getTitle());
                popWindow.dismiss();
            }
        }, this, rlPurpose, pops, "取消", "请选择");
        //  popWindow.setAnimationStyle(R.style.pop_anim);
        popWindow.showAtLocation(rlPurpose, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    }

    public void showRecord(View view) {
        final List<PopBean> pops = new ArrayList<>();
        pops.add(new PopBean("是", 0));
        pops.add(new PopBean("否", 1));
        popWindow = new ListPopWindow(this, new ListPopWindow.OnPopItemClickListener() {
            @Override
            public void onPopItemClick(View view, int position) {
                tvRecord.setText(pops.get(position).getTitle());
                popWindow.dismiss();
            }
        }, this, rlRecord, pops, "取消", "请选择");
        //  popWindow.setAnimationStyle(R.style.pop_anim);
        popWindow.showAtLocation(rlRecord, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    }

    public void showCredit(View view) {
        final List<PopBean> pops = new ArrayList<>();
        pops.add(new PopBean("是", 0));
        pops.add(new PopBean("否", 1));
        popWindow = new ListPopWindow(this, new ListPopWindow.OnPopItemClickListener() {
            @Override
            public void onPopItemClick(View view, int position) {
                tvCredit.setText(pops.get(position).getTitle());
                popWindow.dismiss();
            }
        }, this, rlCredit, pops, "取消", "请选择");
        //  popWindow.setAnimationStyle(R.style.pop_anim);
        popWindow.showAtLocation(rlCredit, Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onBottomClick() {
        popWindow.dismiss();
    }

    @OnClick(R.id.imageView)
    public void onCLickImgHeader(View view) {
        if (userInfo == null) {
            Intent intent = LogInActivity.newIntent(this);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return;
        }
        String[] items = new String[]{"选择照片", "拍照"};
        new AlertDialog.Builder(this)
                .setTitle("选择方式")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                openAlbum();
                                break;
                            case 1:
                                takePicture();
                                break;
                        }
                    }
                }).show();
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        int sysVersion = Build.VERSION.SDK_INT;
        Intent intent;
        if (sysVersion >= 19) {
            intent = new Intent(Intent.ACTION_PICK, null);
        } else {
            intent = new Intent(Intent.ACTION_GET_CONTENT, null);// ACTION_OPEN_DOCUMENT
        }
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                IMAGE_UNSPECIFIED);
        startActivityForResult(intent, REQUEST_ALBUM);
    }

    /**
     * 拍照
     */
    private void takePicture() {
        showCameraAction(picture);
    }

    /**
     * Open camera,android7.0调用相机会出现问题
     */
    private void showCameraAction(File mTmpFile) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(this.getPackageManager()) != null) {
                if (mTmpFile != null) {
                    /*获取当前系统的android版本号*/
                    if (android.os.Build.VERSION.SDK_INT < 24) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
                        startActivityForResult(intent, REQUEST_CAPTURE);
                    } else {
                        Uri uri = FileProvider.getUriForFile(this, ProviderUtil.getFileProviderName(this), mTmpFile);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(intent, REQUEST_CAPTURE);
                    }
                }
            } else {
                TipToast.toast(this, "设备不支持");
            }
        }
    }


    /**
     * 压缩图片
     *
     * @param uri
     */

    public void startPhotoZoom(Uri uri) {
        // 创建File对象，用于存储裁剪后的图片，避免更改原图
        corpFile = new File(getExternalCacheDir(), "crop_image.png");
        try {
            if (corpFile.exists()) {
                corpFile.delete();
            }
            corpFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Uri outputUri = Uri.fromFile(corpFile);
        Intent intent = new Intent(Constants.FLAG_INTENT_CAMERA);
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra(Constants.FLAG_CROP, Constants.FLAG_TRUE);
        intent.putExtra(Constants.FLAG_ASPECT_X, 1);
        intent.putExtra(Constants.FLAG_ASPECT_Y, 1);
        intent.putExtra(Constants.FLAG_OUTPUT_X, 64);
        intent.putExtra(Constants.FLAG_OUTPUT_Y, 64);
        intent.putExtra(Constants.FLAG_RETURN_DATA, true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        startActivityForResult(intent, REQUEST_CROP);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ALBUM:
                if (data != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            case REQUEST_CAPTURE:
                if (resultCode == RESULT_OK) {
                    if (android.os.Build.VERSION.SDK_INT < 24) {
                        startPhotoZoom(Uri.fromFile(picture));
                    } else {
                        Uri uri = FileProvider.getUriForFile(this, ProviderUtil.getFileProviderName(this), picture);
                        startPhotoZoom(uri);
                    }
                }
                break;
            case REQUEST_CROP:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Map<String, RequestBody> params = new HashMap<>();
                        params.put("id", UploadUtils.createBodyFromString(userInfo.getId()));
                        MultipartBody.Part body = UploadUtils.prepareFilePart("file", corpFile.getPath());
                        APIHub.getsInstance().getBaseService().upLoadAvatar(params, body).enqueue(new Callback<Result>() {
                            @Override
                            public void onResponse(Call<Result> call, Response<Result> response) {
                                Result result = response.body();
                                if (result.getCode().equals("200")) {
                                    TipToast.toast(PersionInfoActivity.this, "上传头像成功！");
                                    UserInfo userInfo = new Gson().fromJson(result.getData(), UserInfo.class);
                                    UserDBHelper.getInstance(PersionInfoActivity.this).saveUserInfo(userInfo);
//                                    EventBus.getDefault().post(new UpdateMyFragmentEvent());
                                    initView();
                                } else {
                                    TipToast.toast(PersionInfoActivity.this, result.getRemark().toString());
                                }
                            }

                            @Override
                            public void onFailure(Call<Result> call, Throwable t) {
                                TipToast.toast(PersionInfoActivity.this, "网络连接失败");
                            }
                        });
                    }
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STORAGE_WRITE_ACCESS_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                } else {
                    // Permission Denied
                    takePicture();
                }
                break;
        }
    }

    @OnClick(R.id.btn_modify)
    public void onClickSave(View view) {
        if (checkSave()) {
            Map<String, String> param = new HashMap<String, String>();
            param.put("id", userInfo.getId());
            param.put("name", realName.getText().toString());
//            param.put("phone", telPhone.getText().toString());//电话不可编辑
            param.put("idcard", identify.getText().toString());
            if (!TextUtils.isEmpty(tvJob.getText().toString())) {
                param.put("profession", tvJob.getText().toString());
            }
            if (!TextUtils.isEmpty(tvCulture.getText().toString())) {
                param.put("culture", tvCulture.getText().toString());
            }
            if (!TextUtils.isEmpty(tvPurpose.getText().toString())) {
                param.put("purpose", tvPurpose.getText().toString());
            }
            if (!TextUtils.isEmpty(tvRecord.getText().toString())) {
                param.put("loans", tvRecord.getText().toString());
            }
            if (!TextUtils.isEmpty(tvCredit.getText().toString())) {
                param.put("credit", tvCredit.getText().toString());
            }
            showLoadingDialog();
            APIHub.getsInstance().getBaseService().updateUserInfo(param).enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    dismissLoadingDialog();
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                        TipToast.toast(PersionInfoActivity.this, "修改成功!");
                        UserInfo userInfo = new Gson().fromJson(result.getData(), UserInfo.class);
                        UserDBHelper.getInstance(PersionInfoActivity.this).saveUserInfo(userInfo);
                        finish();
                    } else {
                        TipToast.toast(PersionInfoActivity.this, result.getRemark());
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    dismissLoadingDialog();
                    TipToast.toast(PersionInfoActivity.this, "网络连接失败");
                }
            });
        }
    }

    private boolean checkSave() {
        String name = realName.getText().toString();
        String phone = telPhone.getText().toString();
        String identifyNum = identify.getText().toString();
        if (TextUtils.isEmpty(name)) {
            TipToast.toast(this, "请输入你的姓名");
            return false;
        }
        if (TextUtils.isEmpty(phone)) {
            TipToast.toast(this, "请输入你的手机号");
            return false;
        }
        if (!StringUtils.isPhone(phone)) {
            TipToast.toast(this, "请输入正确的手机号");
            return false;
        }
        if (TextUtils.isEmpty(identifyNum)) {
            TipToast.toast(this, "请输入你的身份证号");
            return false;
        }
        if (!StringUtils.isIdentity(identifyNum)) {
            TipToast.toast(this, "请输入正确的身份证号");
            return false;
        }
        return true;
    }

    @OnClick(R.id.iv_back)
    public void onClickBack(View view) {
        finish();
    }
}
